package com.atguigu.flink0624.chapter08;

import com.atguigu.flink0624.bean.AdsClickLog;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/16 15:43
 */
public class Flink04_Project_High_Ads {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        SingleOutputStreamOperator<String> normal = env
            .readTextFile("input/AdClickLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new AdsClickLog(Long.valueOf(data[0]),
                                       Long.valueOf(data[1]),
                                       data[2],
                                       data[3],
                                       Long.parseLong(data[4]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<AdsClickLog>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getTimestamp())
            )
            .keyBy(log -> log.getUserId() + "_" + log.getAdsId())
            .process(new KeyedProcessFunction<String, AdsClickLog, String>() {
    
                private ValueState<String> yesterdayState;
                private ValueState<Boolean> warnState; // 是否已经加入黑名单
                private ReducingState<Long> clickCountState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    clickCountState = getRuntimeContext()
                        .getReducingState(new ReducingStateDescriptor<Long>("clickCountState",
                                                                            Long::sum,
                                                                            Long.class));
                    warnState = getRuntimeContext().getState(new ValueStateDescriptor<Boolean>("warnState", Boolean.class));
    
                    yesterdayState = getRuntimeContext().getState(new ValueStateDescriptor<String>("yesterdayState", String.class));
                }
                
                @Override
                public void processElement(AdsClickLog value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
    
                    String today = new SimpleDateFormat("yyyyMMdd").format(value.getTimestamp());
                    
                    if(!today.equals(yesterdayState.value())){
                        System.out.println(today);
                        clickCountState.clear();
                        warnState.clear();
                        yesterdayState.update(today);
                    }
                    
    
                    if (warnState.value() == null) {
                        clickCountState.add(1L);
                    }
                    String msg = value.getUserId() +
                        " 对广告: " +
                        value.getAdsId() + " 的点击量是: " +
                        clickCountState.get();
                    
                    if (clickCountState.get() > 99) {
                        if (warnState.value() == null) {
                            ctx.output(new OutputTag<String>("blackList") {}, msg + " 超过了阈值, 加入黑名单");
                            warnState.update(true);
                        }
                    } else {
                        
                        out.collect(msg);
                    }
                    
                }
            });
        
        normal.print("normal");
        normal.getSideOutput(new OutputTag<String>("blackList") {}).print("black");
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
